Write a javascript program that takes a string and returns the longest word length.
Write a javascript program that takes a string and returns the longest word length.
237
14-Apr-2023
Updated on 26-Nov-2023
Aryan Kumar
26-Nov-2023Certainly! You can create a JavaScript program that takes a string and returns the length of the longest word in that string. Here's an example:
In this example, the longestWordLength function takes an input string, splits it into an array of words using a regular expression (/\s+/ to handle different types of whitespace), and then uses the reduce method to find the length of the longest word.
The reduce function takes a callback function with an accumulator (max) and the current element of the array (word). It compares the length of each word with the current maximum length and updates the maximum accordingly.
The example usage demonstrates how to use the function with a sample input string, and the result (length of the longest word) is printed to the console.